package BlogMybatis.blog.controller;


import BlogMybatis.blog.pojo.Message;
import BlogMybatis.blog.service.MessageService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.List;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author Brandt
 * @since 2020-06-17
 */
@Controller
public class MessageController {

    @Autowired
    private MessageService messageService;
    @Value("${comment.avatar}")
    private String avatar;

    @Value("${admin.openid}")
    private String adminOpenid;



    //展示留言列表
    @GetMapping("/Messages")
    public String Message_board(@RequestParam(required = false,defaultValue = "1") int pageNum,Model model){
        PageHelper.startPage(pageNum,8);
        List<Message> messages = messageService.listMessage();
        PageInfo pageInfo = new PageInfo(messages);
        model.addAttribute("messages",pageInfo);
        return "message_board";
    }

    //新增留言
    @PostMapping("/postMessages")
    public String post(Message message, HttpSession session,Model model){
        String loginStatus = (String) session.getAttribute("loginStatus");
        //判断是否QQ用户或者GitHub用户留言
        if(loginStatus != null){
            String openid = (String) session.getAttribute("openid"); //QQ用户的标识
            String avatar = (String) session.getAttribute("avatar");
            String nodeId = (String) session.getAttribute("node_id"); //GitHub用户的标识
            message.setAvatar(avatar);
            //qq用户
            message.setAdminMessage(1);
            if(StringUtils.isNotBlank(nodeId)){
                //GitHub用户
                message.setAdminMessage(3);
            }
            //判断是否博主
            if(adminOpenid.equals(openid)){
                message.setAdminMessage(2);
            }
        }else {
            //游客
            message.setAdminMessage(0);
            message.setAvatar(avatar);
        }
        messageService.saveMessage(message);
        messageService.findParentMessage(message);
        return "redirect:/Message";
    }

    //将数据返回message_board页面的th:fragment="messageList"片段，实现局部刷新
    @GetMapping("/Message")
    public String Message(@RequestParam(required = false,defaultValue = "1") int pageNum,Model model){
        PageHelper.startPage(pageNum,8);
        List<Message> messages = messageService.listMessage();
        PageInfo pageInfo = new PageInfo(messages);
        model.addAttribute("messages",pageInfo);
        return "message_board :: messageList";
    }
}

